package com.mike.web;

import com.mike.config.AppConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

/**
 * @Description 实现web.xml的配置, 完成AppConfig的注册，并基于java代码的方式初始化DispatcherServlet
 * @Date 2021/8/4 14:38
 * @Created by mike
 */
public class MyWebApplicationInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) {
        // 通过注解的方式初始化Spring的上下文
        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        // 注册spring的配置类（替代传统项目中xml的配置）
        ac.register(AppConfig.class);
        ac.refresh();
        // 初始化DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(ac);
        ServletRegistration.Dynamic registration = servletContext.addServlet("/", servlet);
        registration.addMapping("/*");
        registration.setLoadOnStartup(1);
    }
}